package java_class_work.week08.internet.demo1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @Author Tiam
 * @Date 2022/10/31 17:29
 * @Description:
 */
public class UdpReceive {
    public static void main(String[] args) {
        DatagramSocket ds = null;
        try {
            // 1. 创建Socket服务, 并监听端口, 监听8888端口
            ds = new DatagramSocket(8888);
            // 2. 定义数据包, 用于接收发送过来的数据
            byte[] bytes = new byte[1024];
            // 3. 接收数据, 并存入数据包中
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
            ds.receive(dp);
            // 4. 从数据包中取出数据, 同时可获得发送端的数据
            String hostAddress = dp.getAddress().getHostAddress();
            int port = dp.getPort();
            byte[] data = dp.getData();
            String res = new String(data, 0, dp.getLength());

            System.out.println(hostAddress+":"+port+" >> "+res);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 5. 关闭Socket服务
            if(ds != null) ds.close();
        }
    }
}
